//
//  DownLoadController.m
//  Estate
//
//  Created by heyong on 16/7/18.
//  Copyright © 2016年 ttsx. All rights reserved.
//


#import "DownLoadController.h"
#import "downModel.h"
#import "downLoadPdfCell.h"
#import "dataInit.h"
#import "NSString+Extension.h"
#import "DownTypeCell.h"
#import <MJExtension.h>
#import "TTStandardKey.h"
#import "TTStandardFile.h"
#import "TTStandardClass.h"
#import "MJRefresh.h"
#import "PdfDetailViewController.h"
#import "MJPhotoBrowser.h"
#import "LoadingTableViewEmptyView.h"

@interface DownLoadController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating,UISearchBarDelegate,LoadingTableViewEmptyViewDelegate>
/**tableView */
/**注释 */
@property (nonatomic,strong) LoadingTableViewEmptyView *emptyView;
/**搜索参数 */
@property (nonatomic,strong) NSMutableDictionary *searchDic;
/**类型数组 */
@property (nonatomic,strong) NSMutableArray *typeArray;
//标签数组
@property (nonatomic,strong) NSMutableArray *searchTagArray;
//选中的标签数组
@property (nonatomic,strong) NSMutableArray *selectTagArray;
/**结果数组 */
@property (nonatomic,strong) NSMutableArray *dataArray;
/**搜索历史记录 */
@property (nonatomic,strong) NSMutableArray *historyArray;
@property (nonatomic,strong) NSString *historyStr;

/**搜索控制器 */
@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic,assign) int currentPage;
@property (nonatomic,assign) BOOL isFirst;
@property (nonatomic,assign) BOOL isFooter;
@property (nonatomic,assign) BOOL isHidenEmpty;

@end

@implementation DownLoadController
-(void)reloadMyData {
    [self searchPdf:self.searchDic];
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
-(NSMutableDictionary *)searchDic{
    if (!_searchDic) {
        _searchDic = [NSMutableDictionary dictionary];
        [_searchDic setValue:@"" forKey:@"standardClassId"];

    }
    return _searchDic;
}
-(NSMutableArray *)searchTagArray{
    if (!_searchTagArray) {
        _searchTagArray = [NSMutableArray array];
    }
    return _searchTagArray;
}
-(NSMutableArray *)selectTagArray{
    if (!_selectTagArray) {
        _selectTagArray = [NSMutableArray array];
    }
    return _selectTagArray;
}
-(NSMutableArray *)typeArray{
    if (!_typeArray) {
        _typeArray = [NSMutableArray array];
        TTStandardClass *standar = [[TTStandardClass alloc]init];
        standar.id = @"";
        standar.className = @"全部";
        [_typeArray addObject:standar];
    }
    return _typeArray;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64)];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DownTypeCell class]) bundle:nil] forCellReuseIdentifier:@"DownTypeCell"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
    }
    return _tableView;
}
-(UISearchController *)searchController{
    if (!_searchController) {
        //初始化UISearchController并为其设置属性
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        //     [_searchController.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
        //设置代理对象
        _searchController.searchResultsUpdater = self;
        _searchController.searchBar.placeholder = @"请输入想查看的内容！";

        //设置搜索时，背景变暗色
        _searchController.dimsBackgroundDuringPresentation = YES;

        //隐藏导航栏
        _searchController.hidesNavigationBarDuringPresentation = NO;
        //设置搜索框的frame
        _searchController.searchBar.frame = CGRectMake(_searchController.searchBar.frame.origin.x, _searchController.searchBar.frame.origin.y, _searchController.searchBar.frame.size.width, 44.0);
        //将搜索框设置为tableView的组头
        _searchController.searchBar.delegate = self;
        _searchController.searchBar.enablesReturnKeyAutomatically = NO;
        
    }
    return _searchController;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    //添加缓存数据
    [self addData];
    self.currentPage = 1;
    self.isFirst = YES;
    self.navigationItem.titleView = self.searchController.searchBar;
    [self.view addSubview:self.tableView];

    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    self.tableView.mj_footer = footer;
    
    //获取网络数据
    [self getStandardClass];
    [self getStandardKey];
    [self searchPdf:self.searchDic];
}
//添加缓存数据
-(void)addData{
    self.historyArray =  [NSString getArrayWithPlistPath:@"/history.plist"];
    NSArray *standardClass = [NSString getArrayWithPlistPath:@"/standardClass.plist"];
    NSArray *array = [TTStandardClass mj_objectArrayWithKeyValuesArray:standardClass];
    [self.typeArray addObjectsFromArray:array];
    
    NSArray *standardKeys = [NSString getArrayWithPlistPath:@"/standardKey.plist"];
    self.searchTagArray = [TTStandardKey mj_objectArrayWithKeyValuesArray:standardKeys];
    
    
    //无数据提示
    self.emptyView = [[LoadingTableViewEmptyView alloc] initWithLebel:@"网络异常，点击刷新" delegate:self];
    if (self.typeArray.count>0) {
        self.emptyView.frame = CGRectMake(0, 200, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64-200);
    }else{
        self.emptyView.frame = CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64);
    }
    self.isHidenEmpty = YES;
    self.emptyView.hidden = self.isHidenEmpty;
    [self.tableView addSubview:self.emptyView];
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    //注册键盘消失的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        self.tableView.mj_footer.hidden = YES;
        if(self.historyArray.count>0){
            return self.historyArray.count +1;
        }else{
            return 0;
        }
    }else{
        if (self.dataArray.count>0) {
            self.tableView.mj_footer.hidden = NO;
        }else{
            self.tableView.mj_footer.hidden = YES;
        }
        return 2+self.dataArray.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *rid=@"q2e";
    
    if (self.searchController.active) {
        self.emptyView.hidden = YES;
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:rid];
        if(cell==nil){
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault      reuseIdentifier:rid];
        }
        if(self.historyArray.count>0&&indexPath.row == self.historyArray.count){
            cell.textLabel.text=[NSString stringWithFormat:@"清除历史记录"];
        }else{
            cell.textLabel.text=self.historyArray[self.historyArray.count - indexPath.row -1];
        }
        return cell;
    }else{
        self.emptyView.hidden = self.isHidenEmpty;
        if(indexPath.row == 0){
            DownTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownTypeCell"];
            [cell setCellWithtypeArray:self.typeArray itemSize:CGSizeMake(80, 80)searchDic:self.searchDic];
            cell.clickTypeBlock = ^(UIButton *button) {
                TTStandardClass *standardClass = self.typeArray[button.tag-2000];
                [self.searchDic setValue:standardClass.id forKey:@"standardClassId"];
            };
            return cell;
        }else if (indexPath.row == 1){
            DownTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownTypeCell"];
            [cell setCellWithtagArray:self.searchTagArray itemSize:CGSizeMake(80, 80) searchDic:self.searchDic];
            cell.clickTagBlock  = ^(UIButton *button) {
                      TTStandardKey *standardKey = self.searchTagArray[button.tag-1000];
                if (button.selected) {
                    if (![self.selectTagArray containsObject:standardKey.id]) {
                        [self.selectTagArray addObject:standardKey.id];
                    }
                }else{
                    if ([self.selectTagArray containsObject:standardKey.id]) {
                        [self.selectTagArray removeObject:standardKey.id];
                    }
                }
                [self.searchDic setValue:self.selectTagArray forKey:@"standardKeysIds"];
            };
            return cell;
        }else{
            
            static NSString *cellIdentifier=@"downCell";
            downLoadPdfCell *cell;
            cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if(!cell){
                cell=[[downLoadPdfCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            
            BOOL isdown = NO;
            TTStandardFile *downMo=self.dataArray[indexPath.row-2];
            for (downModel *model in self.oldDataArray) {
                if ([downMo.id isEqualToString:model.id]) {
                    isdown = YES;
                    downMo.pdfid = model.pdfId;
                }
            }
            [cell setTitleContent:downMo.filename];
            
            if (isdown) {
                [cell.downBtn setImage:[UIImage imageNamed:@"chakan_1"] forState:UIControlStateNormal];
                cell.detailBlick = ^{
                    PdfDetailViewController *detail=[[PdfDetailViewController alloc] init];
                    detail.filePath=downMo.pdfid;
                    if( [downMo.type isEqualToString:@"pdf"]||[downMo.type isEqualToString:@"PDF"]){
                        detail.fileType=@"pdf";
                        [self.navigationController pushViewController:detail animated:YES];
                    }else{
                        [self clickImageView:downMo.pdfid];
                        detail.fileType=@"png";
                    }
                };
                
            }else{
                 [cell.downBtn setImage:[UIImage imageNamed:@"xiazai_1"] forState:UIControlStateNormal];
                WEAKSELF
                cell.detailBlick = ^{
                    dataInit *pdfInit=[[dataInit alloc]init];
                    [pdfInit downLoadFilePdf:downMo.id andFileName:downMo.filename andView:self.view AndFileType:downMo.type];
                    pdfInit.blockMainTab=^{
                        [LSUtility showToastWithMessage:@"下载完成" inView:self.view Andtime:1.2];
                        if (weakSelf.delegate) {
                            weakSelf.oldDataArray = [weakSelf.delegate didDownComplete];
                             [weakSelf.tableView reloadData];
                        }
                    };
                };
              
            }
            return cell;
        }
    }
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [self.searchDic setValue:searchBar.text forKey:@"filename"];
    //保存历史记录
    if(searchBar.text.length>0){
        [self saveHistory:searchBar.text];
    }
    self.historyStr = searchBar.text;
    [self searchPdf:self.searchDic];
    
}
//点击搜索框
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    [self.tableView reloadData];
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.searchController setActive:NO];
    self.searchController.searchBar.text = self.historyStr;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
//    [self.searchController setActive:NO];
}
-(void)saveHistory:(NSString *)str{
    
    NSString *path = [NSString getPathWith:@"/history.plist"];
    NSMutableArray *array= [NSString getArrayWithPlistPath:@"/history.plist"];
    if ([array containsObject:str]) {
        [array removeObject:str];
    }
    if (array.count>10) {
        [array removeObjectAtIndex:0];
    }
    [array addObject:str];
    [array writeToFile:path atomically:YES];
    self.historyArray = array;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchController.active) {
        if(self.historyArray.count>0&&indexPath.row == self.historyArray.count){
            [self.historyArray removeAllObjects];
            [self.tableView reloadData];
            NSString *path = [NSString getPathWith:@"/history.plist"];
            NSFileManager* fileManager=[NSFileManager defaultManager];
            BOOL blHave=[fileManager fileExistsAtPath:path];
            if (!blHave) {
                return ;
            }else {
                [fileManager removeItemAtPath:path error:nil];
            }
        }else{
            self.searchController.searchBar.text = self.historyArray[self.historyArray.count - indexPath.row -1];
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchController.active) {
        if (indexPath.row == 0) {
            return  50;
        }
    }else{
        if (indexPath.row == 0 || indexPath.row == 1) {
            return  100;
        }
    }
    return 44;
}
-(void)getStandardClass{
    
    [LSHttpTool Post:URL_getStandardClass parameters:nil success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        if([responseObject[@"code"]isEqualToString:@"1"]){
            NSArray *array = [TTStandardClass mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.typeArray removeAllObjects];
            TTStandardClass *standar = [[TTStandardClass alloc]init];
            standar.id = @"";
            standar.className = @"全部";
            [self.typeArray addObject:standar];
            [self.typeArray addObjectsFromArray:array];
            [self.tableView reloadData];
            NSArray *dicArray = responseObject[@"data"];
            NSString *path = [NSString getPathWith:@"/standardClass.plist"];
            if(dicArray&&![dicArray isEqual:[NSNull null]]){
                [dicArray writeToFile:path atomically:YES];
            }
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [LSUtility showToastWithMessage:@"获取分类数据失败" inView:self.view Andtime:1.5];
    }
 ];
}

-(void)getStandardKey{
    [LSHttpTool Post:URL_getStandardKey parameters:nil success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        if([responseObject[@"code"]isEqualToString:@"1"]){
            self.searchTagArray = [TTStandardKey mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.tableView reloadData];
            NSArray *dicArray = responseObject[@"data"];
            NSString *path = [NSString getPathWith:@"/standardKey.plist"];
            if (dicArray&&![dicArray isEqual:[NSNull null]]) {
                [dicArray writeToFile:path atomically:YES];
            }
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [LSUtility showToastWithMessage:@"获取标签数据失败" inView:self.view Andtime:1.5];
    }
  ];
}

-(void)loadMore{
    self.isFooter = YES;
    [self searchPdf:self.searchDic];
}
#pragma mark -搜索
- (void)searchPdf:(NSDictionary *)pdfDic{
  
    if (!self.isFooter) {
        self.currentPage = 1;
        [LSUtility showMBProgress:self.view message:@"查找中..."];
    }
    [pdfDic setValue:@(self.isFirst) forKey:@"isFirst"];
    [pdfDic setValue:@(self.currentPage) forKey:@"page"];
    [pdfDic setValue:@(20) forKey:@"pageSize"];
    if (self.currentPage == 1) {
        [self.dataArray removeAllObjects];
    }
   
    [LSHttpTool Post:URL_getStandardFile parameters:pdfDic success:^(id responseObject) {
        self.isHidenEmpty = YES;
        self.emptyView.hidden = self.isHidenEmpty;
        self.isFirst = NO;

        NSDictionary *dataDic=responseObject[@"data"];
        if([responseObject[@"code"]isEqualToString:@"1"]){
            [LSUtility hideMBProgressNOAnimation:self.view];
             NSMutableArray *array = [TTStandardFile mj_objectArrayWithKeyValuesArray:dataDic[@"rows"]];
            if (self.isFooter) {
                self.isFooter = NO;
                self.currentPage++;
                [self.tableView.mj_footer endRefreshing];
                [self.dataArray addObjectsFromArray:array];
            }else{
                self.dataArray = array;
            }
            if(self.dataArray.count==0){
                [LSUtility showToastWithMessage:@"没有你想要搜索的文件。" inView:self.view Andtime:2];
            }
            
            if (self.dataArray.count >= [dataDic[@"total"] intValue]) {
              [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
        }else{
            [self.tableView.mj_footer endRefreshing];
            [LSUtility hideMBProgressNOAnimation:self.view];
            [LSUtility showToastWithMessage:@"搜索文件失败" inView:self.view Andtime:1.5];
        }
    } failure:^(NSError *error) {
        [LSUtility hideMBProgressNOAnimation:self.view];
        [LSUtility showToastWithMessage:@"网络异常，请稍后重试" inView:self.view Andtime:1.5];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        self.isHidenEmpty = NO;
        self.emptyView.hidden = self.isHidenEmpty;
    }];
}

//点击图片放大显示
-(void)clickImageView:(NSString *)filePath{
    NSMutableArray *photos = [NSMutableArray array];
    
    MJPhoto *photo = [[MJPhoto alloc] init];
    photo.image = [UIImage imageWithContentsOfFile:filePath];
    [photos addObject:photo];
    
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.photos = photos;
    browser.showSaveBtn = NO;
    [browser show];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    //键盘高度
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardFrame.size.height, 0);
    
}
-(void)keyboardWillBeHidden:(NSNotification*)aNotification{
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0,0, 0);

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
